var ctx = window.daijia.ctx;


$(function () {
	
	// 为图片更改添加监听器
	document.getElementById("wechat_qr_file").addEventListener("change", function (e) {
		var file = e.target.files[0];
		uploadFile(ctx + "/setting/uploadWxQrCode", file);
	}, false);

    // 为图片更改添加监听器
    document.getElementById("small_qr_file").addEventListener("change", function (e) {
        var file = e.target.files[0];
        uploadSmall(ctx + "/setting/uploadWxQrCode", file);
    }, false);
	
	$("#certFileButton").click(function () {
    	$("#certFile").click();
    });
	
    $(document).on('change', '#certFile', function () {
        if ($.trim($(this).val())) {
            $.ajaxFileUpload({
                url: ctx+'/common/uploadWxCert',
                secureuri: false,
                fileElementId: 'certFile',
                dataType: 'json',
                success: function (result) {
                    if (result.success) {
                        $.scojs_message("上传成功", $.scojs_message.TYPE_OK);
                        $("#certUrl").val(result.url);
                    }else {
                        $.scojs_message(result.msg, $.scojs_message.TYPE_ERROR);
                    }
                }
            });
        }
    });

})


// 上传文件
function uploadFile(url, file) {
	var formData = new FormData();
	formData.append("file", file);
	var xhr = new XMLHttpRequest();
	xhr.onloadend = complete;
	xhr.open("POST", url, true);
	xhr.send(formData);
}

// 上传成功回调
function complete (event) {
	var response = event.target.responseText;
	var data = JSON.parse(response);
	if (data) {
		if (data.code == 0) {
			console.log("上传成功", data);
			$.scojs_message("上传成功", $.scojs_message.TYPE_OK);
			var pathUrl = data.data;
			$("#wxQrCode_input").val(pathUrl);
			$("#wxQrCode_img").attr("src", ctx + "/" + pathUrl);
		} else {
			$.scojs_message(data.errorMsg, $.scojs_message.TYPE_ERROR);
		}
	} else {
		$.scojs_message("上传失败", $.scojs_message.TYPE_ERROR);
	}
	$("#wechat_qr_file").val("");
}

// 上传文件
function uploadSmall(url, file) {
    var formData = new FormData();
    formData.append("file", file);
    var xhr = new XMLHttpRequest();
    xhr.onloadend = completeSmall;
    xhr.open("POST", url, true);
    xhr.send(formData);
}

// 上传成功回调
function completeSmall (event) {
    var response = event.target.responseText;
    var data = JSON.parse(response);
    if (data) {
        if (data.code == 0) {
            console.log("上传成功", data);
            $.scojs_message("上传成功", $.scojs_message.TYPE_OK);
            var pathUrl = data.data;
            $("#small_input").val(pathUrl);
            $("#wxSmall_img").attr("src", ctx + "/" + pathUrl);
        } else {
            $.scojs_message(data.errorMsg, $.scojs_message.TYPE_ERROR);
        }
    } else {
        $.scojs_message("上传失败", $.scojs_message.TYPE_ERROR);
    }
    $("#small_qr_file").val("");
}